package com.zzyl.serve.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.serve.domain.FamilyMember;
import com.zzyl.serve.dto.MemberLoginDto;
import com.zzyl.serve.mapper.FamilyMemberMapper;
import com.zzyl.serve.service.IFamilyMemberService;
import com.zzyl.serve.util.WeChatUtil;
import com.zzyl.serve.vo.MemberLoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private WeChatUtil weChatUtil;
    @Autowired
    private FamilyMemberMapper familyMemberMapper;
    @Autowired
    private TokenService tokenService;
    private static final List<String> nickNamePool = List.of("生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝");
    @Override
    public MemberLoginVo login(MemberLoginDto dto) {
        //获取openId，判断数据库中是否存在，不存在则保存，存在，如果手机号一致则更新，不一致则不操作
        String openId = weChatUtil.getOpenid(dto.getCode());
        String phone = weChatUtil.getPhone(dto.getPhoneCode());
        LambdaQueryWrapper<FamilyMember> wrapper = Wrappers.<FamilyMember>lambdaQuery().eq(FamilyMember::getOpenId, openId);
        FamilyMember member = familyMemberMapper.selectOne(wrapper);
        if(member == null){
            member = new FamilyMember();
            member.setOpenId(openId);
            member.setPhone(phone);
            //设置姓名为随机+手机后四位
            member.setName(nickNamePool.get((int)(Math.random()* nickNamePool.size()))+phone.substring(phone.length()-4));
            save(member);
        }else if(!phone.equals(member.getPhone())){
            member.setPhone(phone);
            updateById(member);
        }
        MemberLoginVo vo = new MemberLoginVo();
        vo.setNickName(member.getName());
        Map<String,Object> claims = new HashMap<>();
        claims.put("id",member.getId());
        claims.put("name",member.getName());
        String token = tokenService.createToken(claims);
        vo.setToken(token);
        return vo;
    }
}
